package service
{
	import mx.rpc.soap.WebService;
	
	import service.events.NetworkDataEvent;
	import service.interfaces.INetworkCommunication;
	import service.interfaces.INetworkManager;
	import service.network.NetworkFactory;
	import service.util.HTTPStandardURL;
	import service.util.XMLTemplateParser;

	public class NetworkManager implements INetworkManager
	{
		private var webService:INetworkCommunication;
		//TODO Medium priority: check if a poll of INetworkCommunications is required
		//Note: it will be hard to implement the StreamNetwork if a poll will be used, we better not use it
		private var _sessionId:String;
		private var _dataFunction:Function;
		private var _errorFunction:Function;
		
		public function NetworkManager() {
			webService = NetworkFactory.createInstance(NetworkFactory.HTTP);
			webService.addEventListener(NetworkDataEvent.RESULT, onResult);
		}
		
		public function addListeners(dataFunction:Function, errorFunction:Function):void {
			_dataFunction = dataFunction;
			_errorFunction = errorFunction;
		}
		
		public function removeListeners(dataFunction:Function, errorFunction:Function):void {
			if (_dataFunction == dataFunction) {
				_dataFunction = null;
			}
			
			if (_errorFunction == errorFunction) {
				_errorFunction = null;
			}
		}
		
		private function onResult(event:NetworkDataEvent):void {
			var response:XML = event.data;
			
			if (response.ErrorCode.@value.length() > 0) {
				if (_errorFunction != null) {
					_errorFunction(XMLTemplateParser.parseErrorResponse(response));
				}
				return;
			} else {
				if (_dataFunction != null) {
					_dataFunction(new XML(response.Content));
				}
				return;
			}
		}
		
		public function set sessionId(value:String):void {
			_sessionId = value;
		}
		
		public function actionLogin(username:String, password:String):void {
			var xml:XML = XMLTemplateParser.getLoginXML(username, password);
			var url:String = HTTPStandardURL.LOGIN_URL;
			
			webService.send(xml, url);
		}
		
		public function actionLogout():void {
			
			var xml:XML = XMLTemplateParser.getLogoutXML(_sessionId);
			var url:String = HTTPStandardURL.LOGOUT_URL;
			
			webService.send(xml, url);
		}
		
		public function actionGetDomains():void {
			var xml:XML = XMLTemplateParser.getSnippetDomaninXML(_sessionId);
			var url:String = HTTPStandardURL.DOMAIN_URL;
			
			webService.send(xml, url);
		}
		
		public function actionAddSnippet(title:String, domain:String, value:String, tags:String):void {
			var xml:XML = XMLTemplateParser.getAddSnippetXML(_sessionId,title, domain, value, tags);
			var url:String = HTTPStandardURL.ADDSNIPPET_URL;
			trace(xml.toXMLString());
			webService.send(xml, url);			
		}
		
		public function actionAllSnippet():void {
			var xml:XML = XMLTemplateParser.getAllSnippetXML(_sessionId);
			var url:String = HTTPStandardURL.ALLSNIPPETARTICLE_URL;
			webService.send(xml,url);
		}
	}
}